#include "abstracttable.h"

AbstractTable::AbstractTable(const QString &connectionName) :
    m_connectionName(connectionName)
{
}

AbstractTable::~AbstractTable()
{
}

QSqlQuery AbstractTable::TransactionExec(const QString &sqlstr, bool &isOk)
{
    qDebug() << "AbstractTable::TransactionExec:" << sqlstr;
    isOk = false;
    QSqlDatabase db = QSqlDatabase::database(m_connectionName);
    QSqlQuery query(db);
    if (db.transaction()) //事务开启
    {
        if (query.exec(sqlstr))
        {
            if (db.commit())
            {
                qInfo() << "Operation successed!";
                isOk = true;
            }
            else
            {
                //操作失败，将要回滚
                if (!db.rollback())
                {
                    qWarning() << "rollback failed:" << db.lastError().text();
                }
            }
        }
        else
        {
            qWarning() << "exec failed:" << db.lastError().text();
        }
    }
    else
    {
        qWarning() << "transaction failed:" << db.lastError().text();
    }
    return query;
}

bool AbstractTable::FillField(const QString &table, const QVariant &variant, QMap<QString, QString> &fieldMap)
{
    bool bRet = false;
    QString sqlStrq = "SHOW COLUMNS FROM `%1`;";
    QSqlQuery && colQuery = TransactionExec(sqlStrq.arg(table), bRet);
    QVariantMap varMap = variant.toMap();
    while(bRet && colQuery.next())
    {
        QString field = colQuery.value("Field").toString();
        if(varMap.contains(field))
        {
            QVariant value = varMap.value(field);
            switch (value.type())
            {
            case QVariant::String:
            case QVariant::ByteArray:
            {
                fieldMap.insert(QString("`%1`").arg(field), QString("'%1'").arg(value.toString()));
            }
                break;
            case QVariant::Bool:
            case QVariant::Int:
            {
                fieldMap.insert(QString("`%1`").arg(field), QString("%1").arg(value.toInt()));
            }
                break;
            case QVariant::Double:
            {
                fieldMap.insert(QString("`%1`").arg(field), QString("%1").arg(value.toDouble()));
            }
                break;
            default:
                qWarning() << "Unknow type:" << field << value;
                break;
            }
        }
        else
        {
            qInfo() << "not contains field" << field;
        }
    }

    return bRet && (fieldMap.size() > 0);
}
